// dividend.ts
// 导入IndexedDB服务
import { getAllDividends, batchUpdateDividends, type DividendItem } from '@/data/InvestmentDB'
import { queryStockDetailsApi } from '@/api/modules/Rich'

let dividendData: DividendItem[] = []

// 刷新股息数据
export const refreshDividendData = async () => {
  try {
    const data = await getAllDividends()
    dividendData = data
    await fetchDividendData() // 等待数据更新完成
  } catch (error) {
    console.error('刷新股息数据失败:', error)
  }
}

// 获取股息数据并更新
const fetchDividendData = async () => {
  // 常量定义
  const MAX_RETRY = 1 // 重试次数
  const RETRY_DELAY = 1000 // 重试延迟(ms)

  if (dividendData.length === 0) {
    console.log('无股息数据可更新')
    return []
  }

  try {
    // 使用Promise.allSettled确保单个请求失败不影响整体
    const results = await Promise.allSettled(
      dividendData.map(async (item) => {
        const code = item.code
        if (!code || typeof code !== 'string') {
          console.warn('无效的股息代码，跳过更新', item)
          return null
        }

        // 带重试的API请求
        let retryCount = 0
        while (retryCount <= MAX_RETRY) {
          try {
            // 获取股息详情
            const { data } = await queryStockDetailsApi({ code })

            // 更新股息项目数据
            updateDividendItemData(item, data, code)

            return { code, status: 'success', item }
          } catch (error) {
            retryCount++
            if (retryCount > MAX_RETRY) {
              console.error(`获取股息 ${code} 数据失败（已重试${MAX_RETRY}次）:`, error)
              return { code, status: 'error', error }
            }
            console.warn(`获取股息 ${code} 数据失败，正在重试（${retryCount}/${MAX_RETRY}）`)
            await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY))
          }
        }
      }),
    )

    // 筛选成功更新的股息数据
    const updatedDividends = results
      .filter((r) => r.status === 'fulfilled' && r.value?.status === 'success' && r.value.item)
      .map((r) => (r as PromiseFulfilledResult<{ item: DividendItem }>).value.item)

    // 执行批量更新
    if (updatedDividends.length > 0) {
      await batchUpdateDividends(updatedDividends)
      console.log(`已成功批量更新 ${updatedDividends.length} 条股息数据到本地数据库`)
    }

    // 统计更新结果
    const totalCount = dividendData.length
    const successCount = updatedDividends.length
    console.log(`股息数据更新完成: 成功 ${successCount}/${totalCount}`)

    if (totalCount - successCount > 0) {
      console.error(`部分股息数据更新失败 (${totalCount - successCount}/${totalCount})`)
    }

    return results
  } catch (error) {
    console.error('股息数据更新整体失败:', error)
    return []
  }
}

// 更新股息项目数据
const updateDividendItemData = (item: DividendItem, data: any, code: string) => {
  // 基础信息更新
  item.name = data.name || item.name || '未知股票'
  item.code = code // 确保代码正确

  // 股息数据处理
  item.dividendDate = data.dividendDate || item.dividendDate // 除息日
  item.paymentDate = data.paymentDate || item.paymentDate // 派息日
  item.dividendAmount =
    data.dividendAmount !== undefined ? Number(data.dividendAmount) : item.dividendAmount // 每股股息金额
  item.dividendRate =
    data.dividendRate !== undefined ? Number(data.dividendRate) : item.dividendRate // 股息率

  // 计算股息相关指标
  const holdings = Number(item.holdings) || 0
  const dividendAmount = Number(item.dividendAmount) || 0

  // 总股息收入 = 每股股息金额 × 持仓数量
  item.totalDividend =
    holdings > 0 && dividendAmount > 0 ? (dividendAmount * holdings).toFixed(2) : '0.00'

  // 记录最后更新时间
  item.lastUpdated = new Date().toISOString()
}

// 计算股息收益率
export const calculateDividendYield = (dividend: DividendItem): string => {
  const price = Number(dividend.price) || 0
  const dividendAmount = Number(dividend.dividendAmount) || 0

  if (price > 0 && dividendAmount > 0) {
    return ((dividendAmount / price) * 100).toFixed(2)
  }
  return '0.00'
}

// 格式化日期
export const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return '未知'

  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateString
  }
}
